<?php
//by willson 105328468@qq.com 2014/10/13
//member module interface
class cart extends core {
	public $goods_mod;
	public $member_mod;
	public $order_mod;
	public $commission_mod;
	public $coupon_mod;
	public $collect_mod;

	public function __construct() {
		parent::__construct();
		$this->goods_mod = m("goods");
		$this->member_mod = m("member");
		$this->order_mod = m("order");
		$this->commission_mod = m("commission");
		$this->coupon_mod = m("coupon");
		$this->collect_mod = m("collect");
	}

	//购物车数量
	public function total($isFilter=false, $isReturn=false, $checkSpec=true) {
		$goods_id = (isset($_POST['goods_id']) && trim($_POST['goods_id'])) ? trim($_POST['goods_id']) : 0;
		$spec = (isset($_POST['spec']) && trim($_POST['spec'])) ? trim($_POST['spec']) : '';
		//先判断该规格是否还存在
		if ($goods_id && $checkSpec) {
			$sql = "SELECT count(*) FROM {$this->tbp}goods_spec WHERE goods_id='{$goods_id}' AND spec='{$spec}'";
			$count = $this->db->get_var($sql);
			if (!$count) error("该商品规格已下架");
		}
		$quantity = 0;
		$total_price = 0;
		//$sql = "SELECT IFNULL(SUM(quantity),0) FROM {$this->tbp}cart WHERE 1";
		$sql = "SELECT price, quantity FROM {$this->tbp}cart WHERE goods_id>0";
		if ($this->member_id>0) {
			$sql .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
		} else {
			$sql .= " AND session_id='".session_id()."'";
		}
		if ($isFilter) {
			if ($goods_id>0) $sql .= " AND goods_id='{$goods_id}'";
			if ($spec) $sql .= " AND spec='{$spec}'";
		}
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k=>$g) {
				$quantity += $g->quantity;
				$total_price += $g->price * $g->quantity;
			}
		}
		if ($isReturn) {
			return array('quantity'=>$quantity, 'total_price'=>$total_price);
		} else {
			success(array('quantity'=>$quantity, 'total_price'=>$total_price));
		}
	}

	//加入到购物车
	public function add() {
		$goods = (isset($_POST['goods']) && trim($_POST['goods'])) ? stripslashes($_POST['goods']) : '';
		//邀请我的渠道商的店铺id
		//$reseller_id = (isset($_POST['reseller']) && trim($_POST['reseller'])) ? trim($_POST['reseller']) : 0;
		$reseller_id = (isset($_SESSION['reseller_id']) && intval($_SESSION['reseller_id'])) ? intval($_SESSION['reseller_id']) : 0;
		//操作是根据quantity值, 传1:当前操作是购物车修改商品总数量, 0:进行累加(数字)/累减(-数字)
		$edit = (isset($_POST['edit']) && trim($_POST['edit'])) ? trim($_POST['edit']) : 0;

		if ($goods) {
			$goods = json_decode($goods);
			if (is_array($goods) && count($goods)) {
				foreach ($goods as $k=>$g) {
					$sql = "SELECT id, quantity FROM {$this->tbp}cart WHERE goods_id='{$g->goods_id}' AND spec='{$g->spec}'";
					if ($this->member_id>0) {
						$sql .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
					} else {
						$sql .= " AND session_id='".session_id()."'";
					}
					$rs = $this->db->get_row($sql);
					if ($rs) {
						if (!$edit) {
							if (intval($g->quantity)<0 && $rs->quantity-intval($g->quantity)<=0) {
								$sql = "DELETE FROM {$this->tbp}cart WHERE id='{$rs->id}'";
							} else {
								$sql = "UPDATE {$this->tbp}cart SET quantity=quantity+{$g->quantity} WHERE id='{$rs->id}'";
							}
						} else {
							if (intval($g->quantity)<=0) {
								$sql = "DELETE FROM {$this->tbp}cart WHERE id='{$rs->id}'";
							} else {
								$sql = "UPDATE {$this->tbp}cart SET quantity='{$g->quantity}' WHERE id='{$rs->id}'";
							}
						}
						$this->db->query($sql);
					} else {
						$sql = "SELECT price, promote_price, shop_id FROM {$this->tbp}goods WHERE id='{$g->goods_id}'";
						$row = $this->db->get_row($sql);
						if ($row) {
							$price = $this->goods_mod->get_min_price(array($row->price, $row->promote_price));
							$shop_id = $row->shop_id;
							$sql = "INSERT INTO {$this->tbp}cart (member_id, session_id, goods_id, quantity, spec, ip, add_time, shop_id, reseller_id, price)
								VALUES ('{$this->member_id}', '".session_id()."', '{$g->goods_id}', '{$g->quantity}', '{$g->spec}', '{$this->ip}', '".time()."', 
								'{$shop_id}', '{$reseller_id}', '{$price}')";
							$this->db->query($sql);
						}
					}
				}
			}
		}
		$this->total();
	}

	//从购物车删除
	public function delete() {
		$cart_id = (isset($_POST['cart_id']) && trim($_POST['cart_id'])) ? trim($_POST['cart_id']) : 0;
		if ($cart_id<=0) error('数据错误');
		$sql = "DELETE FROM {$this->tbp}cart WHERE id='{$cart_id}'";
		if ($this->member_id>0) {
			$sql .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
		} else {
			$sql .= " AND session_id='".session_id()."'";
		}
		$this->db->query($sql);
		$this->total();
	}

	//购物车首页
	//支持分单，不需要分单，按照默认即可（shop_id=0）
	public function index() {
		//print_r($_SESSION);
		$filter = '';
		if ($this->member_id>0) {
			$filter .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
		} else {
			$filter .= " AND session_id='".session_id()."'";
		}
		$sql = "SELECT COUNT(DISTINCT(shop_id)) FROM {$this->tbp}cart WHERE 1 {$filter}";
		$count = $this->db->get_var($sql);
		if ($count>1) {
			$sql = "SELECT shop_id FROM {$this->tbp}cart WHERE 1 {$filter}";
		} else {
			$sql = "SELECT DISTINCT(shop_id) FROM {$this->tbp}cart WHERE 1 {$filter}";
		}
		//$sql .= " ORDER BY id ASC";
		//exit($sql);
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k=>$s) {
				$sql = "SELECT name, avatar FROM {$this->tbp}shop WHERE id='{$s->shop_id}'";
				$row = $this->db->get_row($sql);
				if ($row) {
					$rs[$k]->shop_name = $row->name;
					$rs[$k]->shop_avatar = $row->avatar;
				}
				$sql = "SELECT c.id, c.goods_id, c.spec, c.quantity, c.reseller_id,
					g.name, g.pic, g.price, g.promote_price, g.stocks
					FROM {$this->tbp}cart c LEFT JOIN {$this->tbp}goods g ON c.goods_id=g.id
					WHERE c.shop_id='{$s->shop_id}' AND g.status='1' {$filter}";
				$goods = $this->db->get_results($sql);
				if ($goods) {
					foreach ($goods as $gk=>$g) {
						//获取价格
						$sql = "SELECT * FROM {$this->tbp}goods_spec WHERE goods_id='{$g->goods_id}' AND spec='{$g->spec}'";
						$row = $this->db->get_row($sql);
						if ($row) {
							$goods[$gk]->price = $this->goods_mod->get_min_price(array($row->price, $row->promote_price));
							$goods[$gk]->stocks = $row->stocks;
						}
					}
				}
				$rs[$k]->goods = $goods;
			}
		}
		$rs = add_domain_deep($rs, array("pic", "pic", "shop_avatar"));
		success($rs);
	}

	//获取tip
    public function tip() {
        $province_id = $this->request->get('province_id', 0);
        $city_id = $this->request->get('city_id', 0);
        $province = SQL::share('province')->where("province_id='{$province_id}'")->val('name');
        $row = SQL::share('service_city sc')
            ->left('city c', 'sc.city_id=c.city_id')
            ->where("c.city_id='{$city_id}'")->row('c.name, sc.end_day');
        $data = array();
        $data['city'] = "{$province} {$row->name}";
        $data['city_name'] = $row->name;
        $data['end_day'] = $row->end_day;

        success($data);
    }


	public function info() {
	    if (isMobile()){
            if (!$this->member_id) script('请先登录账号', 'wap.php?tpl=login');
        }
		$person_id = $this->request->get('person_id', 0);
		$province_id = $this->request->get('province_id', 0);
		$city_id = $this->request->get('city_id', 0);
		$casy_id = $this->request->get('casy_id', 0);
        $month = $this->request->get('month');
        //var_dump($province_id);exit();
		$data = array(
			'person_id'=>$person_id,
			'province_id'=>$province_id,
			'city_id'=>$city_id,
			'casy_id'=>$casy_id,
			'month'=>$month,
			'person'=>'',
			'city'=>'',
			'city_name'=>'',
			'end_day'=>'',
			'casy'=>'',
			'months'=>''
		);
		if ($person_id) {
			$person = SQL::share('member_person')->where("id='{$person_id}' AND status=1")->val('name');
			$data['person'] = $person;
			if (!$person) $data['person_id'] = 0;
		}
		if ($province_id && $city_id) {
			$province = SQL::share('province')->where("province_id='{$province_id}'")->val('name');
			$row = SQL::share('service_city sc')
				->left('city c', 'sc.city_id=c.city_id')
				->where("c.city_id='{$city_id}'")->row('c.name, sc.end_day');
			if ($row){
                $data['city'] = "{$province} {$row->name}";
                $data['city_name'] = $row->name;
                $data['end_day'] = $row->end_day;
            }
		}
		if ($casy_id) {
			$data['casy'] = SQL::share('service_casy')->where("id='{$casy_id}'")->val('name');
		}
		if ($month) {
			$months = explode(',', $month);
			$data['months'] = (count($months)>1?$months[0].' ~ '.$months[count($months)-1]:$months[0]);
		}

		//增加pc需要的数据
        if (!isMobile()){
            $data['person_pc'] = SQL::share('member_person')->where("member_id='{$this->member_id}' AND member_id>0 AND status=1")
                ->order('id DESC')->find();
            $data['service_province'] = SQL::share('service_province sp')
                ->left('province p', 'sp.province_id=p.province_id')
                ->where('status=1')->sort('sp.sort ASC, sp.id ASC')->find('sp.*, p.name');
            $years = array();
            $now = strtotime(date("Y-m",time()));
            for ($i=0; $i<12; $i++) {
                $time = strtotime("+{$i} month", $now);
                $time = date('Y-m-1', $time);
                $time = strtotime($time);
                $month = new stdClass();
                $month->year = date('Y', $time);
                $month->month = substr(strval(date('m', $time)+100), 1, 2);
                $month->disabled = 0;
                $years[] = $month;
            }
            $data['years'] = $years;
            $year = date('Y');
            $month = date('m');
            $data['year_now'] = $year;
            $data['month_now'] = $month;

            //我要续缴
            $order_id = $this->request->get('id');
            if ($order_id){
                $order = SQL::share('order')->where($order_id)->row();
                $data['province_id'] = $order->province;
                $data['person_id'] = $order->person_id;
                $data['city_id'] = $order->city;
                $row = SQL::share('service_city sc')
                    ->left('city c', 'sc.city_id=c.city_id')
                    ->where("c.city_id='{$order->city}'")->row('c.name, sc.end_day');
                if ($row){
                    $data['city_name'] = $row->name;
                }
                $data['casy'] = SQL::share('service_casy')->where("id='{$order->casy_id}'")->val('name');
                $data['casy_id'] = $order->casy_id;
            }
        }
//var_dump($data);exit();

		success($data);
	}
	
	//参保人
	public function person() {
		if ($this->member_id<=0) error('请登录', -100);
		$rs = SQL::share('member_person')->where("member_id='{$this->member_id}' AND member_id>0 AND status=1")->order('id DESC')->find();
		success($rs);
	}

	public function person_edit() {
		if ($this->member_id<=0) error('请登录', -100);
		$id = $this->request->get('id', 0);
		if (IS_POST) {
			$id = $this->request->post('id', 0);
			$name = $this->request->post('name');
			$mobile = $this->request->post('mobile');
			$idcard = $this->request->post('idcard');
			$social_number = $this->request->post('social_number');
			$gjj_number = $this->request->post('gjj_number');
			$idcard_pic1 = $this->request->post('idcard_pic1');
			$idcard_pic2 = $this->request->post('idcard_pic2');
			$type = $this->request->post('type');
			if (!$name || !$mobile || !$idcard || !$idcard_pic1 || !$idcard_pic2 || !$type) error('资料不完整');
			$data = array(
				'member_id'=>$this->member_id,
				'name'=>$name,
				'mobile'=>$mobile,
				'idcard'=>$idcard,
				'social_number'=>$social_number,
				'gjj_number'=>$gjj_number,
				'idcard_pic1'=>$idcard_pic1,
				'idcard_pic2'=>$idcard_pic2,
				'type'=>$type
			);
			if ($id>0) {
				SQL::share('member_person')->where($id)->update($data);
			} else {
				SQL::share('member_person')->insert($data);
			}

            if (isMobile()){
               success('ok');
            }else{
                location('http://huanchuang.softstao.com/wap.php?app=cart&act=person');
            }

		} else if ($id>0) {
			$row = SQL::share('member_person')->where("id='{$id}' AND member_id='{$this->member_id}'")->row();
		} else {
			$row = t('member_person');
		}
		success($row);
	}

	//删除
    public function person_delete() {
        if ($this->member_id<=0) error('请登录', -100);
        $id = $this->request->get('id', 0);
        if ($id){
            $rs = SQL::share('member_person')->delete($id);
            if ($rs){
                if (isMobile()){
                    header("Location:?app=cart&act=info");
                }else{
                    script('删除成功', 'http://huanchuang.softstao.com/wap.php?app=cart&act=person');
                }
            }else{
                error('删除失败');
            }
        }
    }

	public function idcard_pic() {
		$is_wx = (isset($_POST['is_wx']) && intval($_POST['is_wx'])) ? intval($_POST['is_wx']) : 0;
		if ($is_wx) {
			$idcard_pic = $this->request->post('idcard_pic');
			//下载微信图片
			require_once(FRAMEWORK_PATH . '/class/wxapi/config.php');
			$wxapi = new wechatCallbackAPI();
			$json = $wxapi->access_token();
			$access_token = $json['access_token'];
			$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$idcard_pic}";
			$data = $wxapi->downloadFile($url);
			//$avatar = upload_obj_file($data, 'avatar', 'body', false); //保存在本地
			$idcard_pic = upload_obj_file($data, 'avatar', 'body'); //上传到又拍云
		} else {
			$idcard_pic = $this->request->file('idcard', 'idcard_pic');
		}
		if (!$idcard_pic) error('请选择图片');
		success($idcard_pic);
	}
	public function person_type() {
		success('ok');
	}

	//参保地
	public function province() {
		$rs = SQL::share('service_province sp')
			->left('province p', 'sp.province_id=p.province_id')
			->where('status=1')->sort('sp.sort ASC, sp.id ASC')->find('sp.*, p.name');
		success($rs);
	}

	public function city() {
		$province_id = $this->request->get('province_id', 0);
		if ($province_id<=0) error('数据错误');

        $rs = SQL::share('service_city sc')
            ->left('city c', 'sc.city_id=c.city_id')
            ->left('service_province sp', 'sp.id=sc.parent_id')
            ->left('province p', 'sp.province_id=p.province_id')
            ->where("sp.province_id='{$province_id}'")->sort('sc.sort ASC, sc.id ASC')
            ->find('sc.*, c.name, sp.province_id, p.name as province_name');


		success($rs);
	}

	//参保方案
	public function casy() {
		$gjj_price = 0;
		$city_id = $this->request->get('city_id', 0);
		$person_id = $this->request->get('person_id', 0);
		if ($city_id<=0) error('数据错误');
		$rs = SQL::share('service_casy sa')
			->left('service_city sc', 'service_city_id=sc.id')
			->where("sc.city_id='{$city_id}'")->sort('sa.id ASC')->find('sa.*');
		$row = SQL::share('service_city')->where("city_id='{$city_id}'")->row();
		$gjj_price = $this->_get_gjj_price($city_id, $person_id);
		//$collect = SQL::share('collect')->where("city_id='{$city_id}' AND idcard='{$idcard}'")->sort('id DESC')->row();
		// print_r($row);exit;
		success(array('casy'=>$rs, 'row'=>$row, "gjj_price"=>$gjj_price));
	}

	//pc社保城市最低基数
    public function casy_money() {
	    $casy_id = $this->request->get('casy_id');
        $money = SQL::share('service_casy')->where("id='{$casy_id}'")->val('money');
        success($money);
    }


	public function casy_detail() {
		$casy_id = $this->request->get('casy_id', 0);
		$gjj_value = $this->request->get('gjj', 0);
		if ($casy_id<=0) error('数据错误');
		$name = SQL::share('service_casy')->where($casy_id)->val('name');
		$rs = SQL::share('service_casy_detail')->where("casy_id='{$casy_id}'")->sort('id ASC')
			->find('*, TRUNCATE(money*(firm/100),2) as firm_money, TRUNCATE(money*(person/100),2) as person_money');
		
		$total_price = $total = $gjj_total = $firm_total = $person_total = 0;
		if ($rs) {
			foreach ($rs as $k=>$g) {
				$firm_total = bcadd($firm_total, $g->firm_money, 2);
				$person_total = bcadd($person_total, $g->person_money, 2);
			}
			
			$casy = SQL::share('service_city sc')->left('service_casy c', 'sc.id=service_city_id')
				->where("c.id='{$casy_id}'")->row('sc.money, sc.firm, sc.person');
			$gjj = new stdClass();
			$gjj->name = '公积金';
			//$gjj->money = $casy->money;
			$gjj->money = $gjj_value;
			$gjj->firm = $casy->firm;
			$gjj->person = $casy->person;
			$gjj->firm_money = strval(round($gjj->money*($gjj->firm/100),2));
			$gjj->person_money = strval(round($gjj->money*($gjj->person/100),2));
			$rs[] = $gjj;
			
			$total = bcadd($firm_total, $person_total, 2);
			$gjj_total = bcadd($gjj->firm_money, $gjj->person_money, 2);
			$total_price = bcadd($total, $gjj_total, 2);
		}

		//PC数据处理
        if (!isMobile()){
		    if ($rs){
		        foreach ($rs as $k => $g){
                    $g->firm_money = number_format($g->firm_money, 2);
                    $g->person_money = number_format($g->person_money, 2);
                }
            }
        }

		success(array('rs'=>$rs, 'name'=>$name,
			'total_price'=>$total_price, 'total'=>$total, 'gjj_total'=>$gjj_total, 'firm_total'=>$firm_total, 'person_total'=>$person_total));
	}
	
	//参保月份
	public function month() {
		$person_id = $this->request->get('person_id', 0);
		$city_id = $this->request->get('city_id', 0);
		if ($person_id<=0 || $city_id<=0) error('请先选择参保人与参保地');
		//$now = time();
		$now = strtotime(date("Y-m-1",time()));
		$idcard = SQL::share('member_person')->where($person_id)->val('idcard');
		$order_month = SQL::share('collect')->where("city_id='{$city_id}' AND idcard='{$idcard}'")->sort('id DESC')->val('month');
		$order_month = explode(',', str_replace('，', ',', $order_month));
		$order_month = strtotime($order_month[count($order_month)-1]);
		$end_day = SQL::share('service_city')->where("city_id='{$city_id}'")->val('end_day');
		if (intval(date('Ym',$order_month))<=intval(date('Ym')) && intval($end_day)<intval(date('d'))) $now = strtotime("+1 month", $now);
		$now = strtotime(date('Y-m', $now));
		if ($now<=$order_month) {
			$now = $order_month;
			$now = strtotime("+1 month", $now); //$order_month为订单最后购买日期，所以由下个月开始买
			if (intval(date('Ym',$now))<=intval(date('Ym')) && intval($end_day)<intval(date('d'))) $now = strtotime("+1 month", $now); //如果已经超过可买日子，就只能从下个月买
		}
		$years = array();
		for ($i=0; $i<12; $i++) {
			$time = strtotime("+{$i} month", $now);
			$time = date('Y-m-1', $time);
			$time = strtotime($time);
			$month = new stdClass();
			$month->year = date('Y', $time);
			$month->month = substr(strval(date('m', $time)+100), 1, 2);
			$month->disabled = 0;
			$years[] = $month;
		}
		$year = date('Y');
		$month = date('m');
		$constant_buy = $this->collect_mod->constant_buy($city_id, $idcard, $years[0]->year.'-'.$years[0]->month);
		$min_months = 1;
		if (!$constant_buy) $min_months = intval(SQL::share('service_city')->where("city_id='{$city_id}'")->val('min_months'));
		success(compact('years', 'year', 'month', 'min_months'));
	}
	
	//检测是否首次必须购买多个月
	public function check_min_months($city_id=0, $person_id=0, $months='', $is_show=true) {
		if ($city_id<=0) {
			$city_id = $this->request->get('city_id', 0);
			$person_id = $this->request->get('person_id', 0);
			$months = $this->request->get('months');
		}
		if ($city_id<=0 || $person_id<=0 || !strlen($months)) error('缺少数据');
		$months = explode(',', $months);
		$idcard = SQL::share('member_person')->where($person_id)->val('idcard');
		$min_months = intval(SQL::share('service_city')->where("city_id='{$city_id}'")->val('min_months'));
		if (!strlen($idcard) || $min_months<=0) error('数据错误');
		$constant_buy = $this->collect_mod->constant_buy($city_id, $idcard, $months[0]);
		if (!$constant_buy && count($months)<$min_months) error("该城市必须购买{$min_months}个月及以上");
		if ($is_show) success('ok');
	}
	
	//同一个身份证号码，同一个城市，只能按照初次购买的社保、公积金方案续费，不能修改社保公积金方案续费
	public function get_last() {
		if ($this->member_id<=0) error('请登录', -100);
		$person_id = $this->request->get('person_id', 0);
		$city_id = $this->request->get('city_id', 0);
		$idcard = SQL::share('member_person')->where($person_id)->val('idcard');
		$order = SQL::share('collect c')->left('service_casy sc', 'sc.id=c.casy_id')
			->where("c.city_id='{$city_id}' AND idcard='{$idcard}'")->sort('c.id DESC')->row('c.casy_id, c.gjj_price as gjj, sc.name as casy_name');
		if ($order) $order->gjj = $this->_get_gjj_price($city_id, $person_id);
		success($order);
	}

	//获取公积金的费用
	private function _get_gjj_price($city_id, $person_id){
		$gjj_price = 0;
		$row = SQL::share('service_city')->where("city_id='{$city_id}'")->row();
		if ($row) {
			$idcard = SQL::share('member_person')->where($person_id)->val("idcard");
			if ($idcard) {
				$gjj_price = SQL::share('collect')->where("city_id='{$city_id}' AND idcard='{$idcard}'")->sort('id DESC')->val("gjj_price");
				$gjj_price = floatval($gjj_price) * 100 / ($row->person + $row->firm);
			}
		}
		return $gjj_price;
	}

	//结算接口
	public function jiesuan() {
		if ($this->member_id<=0) error('请登录', -100);
		$person_id = $this->request->post('person_id', 0);
		$province_id = $this->request->post('province_id', 0);
		$city_id = $this->request->post('city_id', 0);
		$casy_id = $this->request->post('casy_id', 0);
		$gjj_val = $this->request->post('gjj', 0, 'float');
		$month = $this->request->post('month');

		if ($person_id<=0 || $province_id<=0 || $city_id<=0 || $casy_id<=0 || !$month) error('数据错误');

		//查看参保人所选的城市参保方案是否已经存在汇总列表里面
        $idcard = SQL::share('member_person')->where($person_id)->val('idcard');
        $order = SQL::share('collect')->where("city_id='{$city_id}' AND idcard='{$idcard}'")->sort('id DESC')->row();

        if ($order){
            //已存在，则需和上次购买的社保相同
            if ($casy_id != $order->casy_id){
                error('请按照上次购买的参保方案进行续费');
            }
        }

		$this->check_min_months($city_id, $person_id, $month, false);
		
		//同一个身份证号码，同一个城市，只能按照初次购买的社保、公积金方案续费，不能修改社保公积金方案续费
		$service_city = SQL::share('service_city')->where("city_id='{$city_id}'")->row();
		$idcard = SQL::share('member_person')->where($person_id)->val('idcard');
		//$order = SQL::share('order')->where("member_id='{$this->member_id}' AND city='{$city_id}' AND idcard='{$idcard}'")->sort('id DESC')->row();
		// $collect = SQL::share('collect')->where("member_id='{$this->member_id}' AND city_id='{$city_id}' AND idcard='{$idcard}'")->sort('id DESC')->row();
		$collect = SQL::share('collect')->where("city_id='{$city_id}' AND idcard='{$idcard}'")->sort('id DESC')->row();
		// echo SQL::share()->sql;exit;
		$months = explode(',', $month);

		$constant_buy = $this->collect_mod->constant_buy($city_id, $idcard, $months[0]);
		if ($collect && $constant_buy) {
			$current_gjj = round($gjj_val*($service_city->firm/100) + $gjj_val*($service_city->person/100));
			$last_gjj = round($collect->gjj_price);
			if ($last_gjj==0 && $current_gjj>0) error('上次下单没有购买公积金，只能按上次续费');
			if ($last_gjj>0 && $current_gjj==0) error('上次下单购买了公积金，只能按上次续费');
			//公积金只能按上次购买
			if ($last_gjj>0 && $current_gjj>0 && $last_gjj!=$current_gjj) {
				error("请按上次购买的公积金费用续费（{$last_gjj}元），如要修改请联系客服");
			}
		}
		
		$months = explode(',', $month);
		$person = SQL::share('member_person')->where($person_id)->row();
		$province = SQL::share('province')->where("province_id='{$province_id}'")->val('name');
		$city = SQL::share('city')->where("city_id='{$city_id}'")->val('name');
		
		$rs = SQL::share('service_casy_detail')->where("casy_id='{$casy_id}'")
			->find('*, TRUNCATE(money*(firm/100),2) as firm_money, TRUNCATE(money*(person/100),2) as person_money');
		$total_price = $total = $gjj_total = $firm_total = $person_total = 0;
		if ($rs) {
			foreach ($rs as $k=>$g) {
				$firm_total = bcadd($firm_total, $g->firm_money, 2);
				$person_total = bcadd($person_total, $g->person_money, 2);
			}
			$casy = SQL::share('service_city sc')->left('service_casy c', 'sc.id=c.service_city_id')
				->where("c.id='{$casy_id}'")->row('sc.money, sc.firm, sc.person, c.name, c.money as casy_money');
			$gjj = new stdClass();
			$gjj->name = '公积金';
			//$gjj->money = $casy->money;
			$gjj->money = $gjj_val;
			$gjj->person = $casy->person;
			$gjj->firm = $casy->firm;
			$gjj->person_money = bcmul($gjj->money, bcdiv($gjj->person,100,2), 2);
			$gjj->firm_money = bcmul($gjj->money, bcdiv($gjj->firm,100,2), 2);
			$gjj_total = round(bcmul(bcadd($gjj->person_money, $gjj->firm_money, 2), count($months), 2), 2);
			$total = bcmul(bcadd($firm_total, $person_total, 2), count($months), 2);
			$total_price = bcadd($total, $gjj_total, 2);
		}
		
		//$service_money = bcmul($service_city->service_money, count($months), 2);
		$service_money = $this->_get_service_money($city_id, count($months));
		if ($gjj_total>0) {
			//$gjj_service_money = bcmul($service_city->gjj_service_money, count($months), 2);
			$gjj_service_money = $this->_get_service_money($city_id, count($months), "gjj");
		} else {
			$gjj_service_money = 0;
		}

		//优惠卷
        $now = time();
        $coupon = SQL::share('coupon_sn cs')->left('coupon c', 'cs.coupon_id=c.id')
            ->where("cs.member_id='{$this->member_id}' AND cs.member_id>'0' AND cs.status=1 AND cs.times!=0 AND c.status=1 
                AND c.begin_time<='{$now}' AND (c.end_time>='{$now}' OR c.end_time=0 OR c.handy_time>0) AND c.offline_use=0")
            ->find('cs.*, c.name, c.type, c.begin_time, c.end_time, c.min_price, c.permit_goods, c.handy_time');
		//显示该城市范围的优惠卷
		if ($coupon){
		    foreach ($coupon as $k => $g){
		        $c_id = SQL::share('coupon_city')->where("coupon_id='{$g->coupon_id}'")->find('city_id');
		        if ($c_id){
                    $c_id = object_to_array($c_id);
                    //转为一维数组
                    $c_id = array_reduce($c_id, function ($result, $value) {
                        return array_merge($result, array_values($value));
                    }, array());
                    if (in_array($city_id, $c_id)){
                        $coupon[$k]->is_city = 1;
                    } else{
                        $coupon[$k]->is_city = 0;
                    }
                }else{
                    $coupon[$k]->is_city = 1;
                }
            }
        }

		$total_price = bcadd($total_price, ($service_money+$gjj_service_money), 2);
		success(array('name'=>$person->name, 'idcard'=>$person->idcard, 'type'=>$person->type, 'city'=>$province.' '.$city,
			'service_money'=>strval(number_format($service_money,2,'.','')),
			'gjj_service_money'=>strval(number_format($gjj_service_money,2,'.','')),
			'month'=>(count($months)>1?$months[0].' ~ '.$months[count($months)-1]:$months[0]),
			'total'=>strval(number_format($total,2,'.','')),
			'gjj_total'=>strval(number_format($gjj_total,2,'.','')),
			'gjj_base_money'=>strval(number_format($gjj->money,2,'.','')),
			'coupon'=>$coupon,
			'social_number'=>$person->social_number,
            'gjj_number'=>$person->gjj_number,
            'casy_name'=>$casy->name,
            'casy_money'=>$casy->casy_money,
            'person_id'=>$person_id,
            'province_id'=>$province_id,
            'city_id'=>$city_id,
            'gjj'=>$gjj_val,
            'casy_id'=>$casy_id,
            'months'=>$month,
			'total_price'=>strval(number_format($total_price,2,'.',''))));
	}

	//下单接口
    //登录测试
    public function login() {
	    success('ok');
    }
    //订单完成处理
    public function order_chuli() {
        $order_id = $this->request->get('id');
        $pay_method = $this->request->get('pay_method');

        if (empty($order_id) || empty($pay_method)) error('数据错误');
        //更改订单状态
        SQL::share('order')->where("id='{$order_id}'")->update(array('status'=>1, 'pay_method'=>$pay_method));

        $order = SQL::share('order')->where("id='{$order_id}'")->row();
        //调用订单完成后处理
        $this->order_complete(true, $order->order_sn);
    }
    //订单完成显示页面
    public function order_ok(){
        success('ok');
    }
	public function order($is_show=true) {
		$person_id = $this->request->post('person_id', 0);
		$province_id = $this->request->post('province_id', 0);
		$city_id = $this->request->post('city_id', 0);
		$casy_id = $this->request->post('casy_id', 0);
		$gjj_val = $this->request->post('gjj', 0);
		$month = $this->request->post('month');
		$c_sn = $this->request->post('sn');
        $pay_method = $this->request->post('pay_method', 'wxpay_h5');

        if ($person_id<=0 || $province_id<=0 || $city_id<=0 || $casy_id<=0 || !$month) error('请选择或填写必要的参保信息');
		
		$months = explode(',', $month);
		$person = SQL::share('member_person')->where($person_id)->row();
		$service_city = SQL::share('service_city')->where("city_id='{$city_id}'")->row('service_money, gjj_service_money');
		$province = SQL::share('province')->where("province_id='{$province_id}'")->val('name');
		$city = SQL::share('city')->where("city_id='{$city_id}'")->val('name');
		
		$rs = SQL::share('service_casy_detail')->where("casy_id='{$casy_id}'")
			->find('*, TRUNCATE(money*(firm/100),2) as firm_money, TRUNCATE(money*(person/100),2) as person_money');
		$social_price = $total_price = $total = $gjj_total = $firm_total = $person_total = 0;
		//单个月的费用
		$month_social_price = $month_gjj_price = $month_social_service_money = $month_gjj_service_money = 0;
		if ($rs) {
			foreach ($rs as $k=>$g) {
				$firm_total = bcadd($firm_total, $g->firm_money, 2);
				$person_total = bcadd($person_total, $g->person_money, 2);
			}
			$casy = SQL::share('service_city sc')->left('service_casy c', 'sc.id=service_city_id')
				->where("c.id='{$casy_id}'")->row('sc.money, sc.firm, sc.person');
			$gjj = new stdClass();
			$gjj->name = '公积金';
			//$gjj->money = $casy->money;
			$gjj->money = $gjj_val;
			$gjj->firm = $casy->firm;
			$gjj->person = $casy->person;
			$gjj->firm_money = strval(round($gjj->money*($gjj->firm/100),2));
			$gjj->person_money = strval(round($gjj->money*($gjj->person/100),2));
			$social_price = bcadd($firm_total, $person_total, 2);
			$total = bcmul($social_price, count($months), 2);
			$gjj_total = bcmul(bcadd($gjj->firm_money, $gjj->person_money, 2), count($months), 2);
			$total_price = bcadd($total, $gjj_total, 2);
			//单月费用
			$month_social_price = $social_price;
			$month_gjj_price = $gjj->firm_money + $gjj->person_money;
		}
		// $service_money = bcmul($service_city->service_money, count($months), 2);
		$service_money = $this->_get_service_money($city_id, count($months));
		$month_social_service_money = $this->_get_service_money($city_id, 1);
		// $gjj_service_money = bcmul($service_city->gjj_service_money, count($months), 2);
		if ($gjj_total>0) {
			$gjj_service_money = $this->_get_service_money($city_id, count($months), "gjj");
			$month_gjj_service_money = $this->_get_service_money($city_id, 1, "gjj");
		} else {
			$gjj_service_money = 0;
			$month_gjj_service_money = 0;
		}
		$total_price = bcadd($total_price, ($service_money+$gjj_service_money), 2);

		//优惠卷
        if ($c_sn && $total_price) {
            $coupons = $this->coupon_mod->check_coupons($c_sn, $total_price, $city_id);
            $coupon_money = SQL::share('coupon_sn')->where("sn='{$coupons->sn}'")->val('coupon_money');
            if ($coupon_money){
                $total_price = $total_price - $coupon_money;
            }
            if ($total_price < 0) $total_price = 0;
        }

        $data = array('name'=>$person->name, 'idcard'=>$person->idcard, 'type'=>$person->type, 'city'=>$province.' '.$city,
			'service_money'=>strval(number_format($service_money,2,'.','')),
			'gjj_service_money'=>strval(number_format($gjj_service_money,2,'.','')),
			'month'=>(count($months)>1?$months[0].' ~ '.$months[count($months)-1]:$months[0]),
			'total'=>strval(number_format($total,2,'.','')),
			'gjj_total'=>strval(number_format($gjj_total,2,'.','')),
			'total_price'=>strval(number_format($total_price,2,'.','')));
		$_SESSION['order_data'] = $data;
		
		$order_sn = generate_order_sn();

		if (empty($coupon_money)){
            $coupon_money = 0;
        }

		$data = array(
			'member_id'=>$this->member_id,
			'parent_order_sn'=>$order_sn,
			'order_sn'=>$order_sn,
			'pay_order_sn'=>$order_sn,
			'total_price'=>$total_price,
			'gjj'=>$gjj_val,
			'gjj_total'=>$gjj_total,
			'service_money'=>$service_city->service_money,
			'service_money_total'=>$service_money,
			'gjj_service_money'=>$service_city->gjj_service_money,
			'gjj_service_money_total'=>$gjj_service_money,
			'pay_method'=>$pay_method,
			'name'=>$person->name,
			'mobile'=>$person->mobile,
			'idcard'=>$person->idcard,
			'person_id'=>$person_id,
			'province'=>$province_id,
			'city'=>$city_id,
			'casy_id'=>$casy_id,
			'month'=>$month,
			'ip'=>$this->ip,
			'status'=>0,
			'add_time'=>time(),
            'used_coupon'=>$coupon_money
		);
		$order_id = SQL::share('order')->insert($data);

		//插入/更新汇总临时表
		$collect = SQL::share('collect_temporary')->where("city_id='{$city_id}' AND idcard='{$person->idcard}'")->row('id');
		$begin_time = strtotime(date('Y-m-d'));
		$end_time = $months[count($months)-1];
		$end_time = strtotime("{$end_time}-01 +1 month -1 day");
		$m = $g = array();
		foreach ($months as $mon) {
			//$mos = explode('-', $mon);
			//$m[] = strval(intval($mos[1]));
			$m[] = $mon;
			if (floatval($gjj_total)>0) $g[] = $mon;
			if (floatval($gjj_total)>0) $g[] = $mon;
		}
		$member_name = strlen($this->member_name) ? $this->member_name : $this->member_nick_name;
		// $gstatus = floatval($gjj_total)>0 ? 0 : 5;
		if ($collect) {
			SQL::share('collect_temporary')->where($collect->id)->update(array('member_type'=>'本站', 'order_id'=>$order_id, 'end_time'=>$end_time,
				'social_number'=>$person->social_number, 'gjj_number'=>$person->gjj_number, 'member_name'=>$member_name, 'person_type'=>$person->type,
				'mobile'=>$person->mobile, 'social_price'=>$month_social_price, 'gjj_price'=>$month_gjj_price, 'service_price'=>$month_social_service_money, 'gjj_service_price'=>$month_gjj_service_money,
				'total_price'=>$total_price, 'month'=>implode('，', $m), 'gmonth'=>implode('，', $g), 'casy_id'=>$casy_id));
		} else {
			SQL::share('collect_temporary')->insert(array('order_id'=>$order_id, 'city_id'=>$city_id, 'member_type'=>'本站', 'member_id'=>$this->member_id,
				'member_name'=>$member_name, 'begin_time'=>$begin_time, 'end_time'=>$end_time, 'real_name'=>$person->name, 'idcard'=>$person->idcard,
				'social_number'=>$person->social_number, 'gjj_number'=>$person->gjj_number, 'person_type'=>$person->type, 'mobile'=>$person->mobile,
				'social_price'=>$month_social_price, 'gjj_price'=>$month_gjj_price, 'service_price'=>$month_social_service_money, 'gjj_service_price'=>$month_gjj_service_money,
				'total_price'=>$total_price, 'month'=>implode('，', $m), 'gmonth'=>implode('，', $g), 'casy_id'=>$casy_id, 'add_time'=>time()));
		}

        //使用优惠券
        $this->coupon_mod->using($c_sn, $this->member_id);

		//要写入session，by willson 2015/9/2
		$pay_method_name = '';
		switch ($pay_method) {
			case 'alipay':$pay_method_name = '支付宝支付';break;
			case 'wxpay':case 'wxpay_h5':$pay_method_name = '微信支付';break;
			case 'yue':$pay_method_name = '余额支付';break;
			case 'integral':$pay_method_name = '积分支付';break;
		}
		$_SESSION['order_sn'] = $order_sn;
		$_SESSION['total_price'] = $total_price;
		$_SESSION['pay_method_name'] = $pay_method_name;
		$_SESSION['program_order'] = $this->is_mini; //小程序订单

		if ($is_show) {
			//如果有多个订单，order_id为最后一个
			success(array("order_id"=>$order_id, "order_sn"=>$order_sn, "total_price"=>$total_price));
		}
	}


	//下单接口,微信端用,因为涉及到需要即时跳转去支付
	public function order_pay() {
		//判断是否提交过来，如果是，表示是新订单，清空订单SESSION
		if (IS_POST) {
			$_SESSION['order_data'] = '';
			$_SESSION['order_sn'] = '';
			$_SESSION['total_price'] = '';
			$_SESSION['pay_method_name'] = '';
			$_SESSION['program_order'] = '';
		}
        $order_data = isset($_SESSION['order_data']) ? $_SESSION['order_data'] : NULL;
		$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
		$total_price = (isset($_SESSION['total_price']) && floatval($_SESSION['total_price'])) ? floatval($_SESSION['total_price']) : 0;
		$pay_method_name = (isset($_SESSION['pay_method_name']) && trim($_SESSION['pay_method_name'])) ? trim($_SESSION['pay_method_name']) : '';
		$program_order = (isset($_SESSION['program_order']) && trim($_SESSION['program_order'])) ? intval($_SESSION['program_order']) : 0;
		$order_body = WEB_TITLE.' - 订单';
		if ($order_sn=='' || $total_price<=0) {
			$this->order(false);
            $order_data = isset($_SESSION['order_data']) ? $_SESSION['order_data'] : NULL;
			$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
			$total_price = (isset($_SESSION['total_price']) && trim($_SESSION['total_price'])) ? floatval($_SESSION['total_price']) : 0;
			$pay_method_name = (isset($_SESSION['pay_method_name']) && trim($_SESSION['pay_method_name'])) ? trim($_SESSION['pay_method_name']) : '';
			$program_order = (isset($_SESSION['program_order']) && trim($_SESSION['program_order'])) ? intval($_SESSION['program_order']) : 0;
		}
		if ($order_sn=='' || $total_price<=0) {
			error('信息错误！');
		}

		//注释这两行，因为$pay_method_name从微信回调时是没有任何内容的;
		//by willson 2015-09-02
		//$_SESSION['pay_method_name'] = $pay_method_name;
		//$_SESSION['total_price'] = $total_price;
		/**
		 * JS_API支付demo
		 * ====================================================
		 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
		 * 成功调起支付需要三个步骤：
		 * 步骤1：网页授权获取用户openid
		 * 步骤2：使用统一支付接口，获取prepay_id
		 * 步骤3：使用jsapi调起支付
		*/
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");

		//使用jsapi接口
		$jsApi = new JsApi_pub();
		$openid = '';

		if ($program_order==0) {
			//=========步骤1：网页授权获取用户openid============
			//通过code获得openid
			$code = (isset($_GET['code']) && trim($_GET['code'])) ? trim($_GET['code']) : '';
			if (!$code){
				//触发微信返回code码
				$url = $jsApi->createOauthUrlForCode(urlencode(https().$_SERVER['SERVER_NAME']."/wap.php?app=cart&act=order_pay"));
				//echo $url;
				//exit;
				header("Location: {$url}");
				exit;
			}else{
				//获取code码，以获取openid
				//echo $code;
				//exit;
				$jsApi->setCode($code);
				$openid = $jsApi->getOpenid();
			}
		} else {
			$sql = "SELECT mini_openid FROM {$this->tbp}member WHERE id='{$this->member_id}'";
			$openid = $this->db->get_var($sql);
		}

		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();

		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$unifiedOrder->setParameter("openid", "$openid");
		$unifiedOrder->setParameter("body", "$order_body");//商品描述
		if ($order_sn=='') {
			//自定义订单号，此处仅作举例
			$timeStamp = time();
			$order_sn = WxPayConf_pub::APPID."$timeStamp";
		}
		$unifiedOrder->setParameter("out_trade_no", "$order_sn");//商户订单号
		$unifiedOrder->setParameter("total_fee", $total_price*100);//总金额,单位:分
		$unifiedOrder->setParameter("notify_url", https().$_SERVER['SERVER_NAME']."/wx_notify_url.php");//通知地址
		$unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID
		if ($program_order!=0) {
			$unifiedOrder->setMiniProgram(true);
			$jsApi->setMiniProgram(true);
		}

		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);

		$jsApiParameters = $jsApi->getParameters();
		//exit($jsApiParameters);
		success($jsApiParameters, '成功', 0, array("order_sn"=>$order_sn, "total_price"=>$total_price, "pay_method_name"=>$pay_method_name, "order_data"=>$order_data));
	}

	//扫码支付
	public function native() {
		$order_sn = (isset($_GET['order_sn']) && trim($_GET['order_sn'])) ? trim($_GET['order_sn']) : '';
		$url = (isset($_GET['url']) && trim($_GET['url'])) ? trim($_GET['url']) : '';
		success(array('order_sn'=>$order_sn, 'url'=>$url));
	}

	//wiexin获取二维码支付
    public function getPayQrcode() {
        function curlGet($url) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            return curl_exec($ch);
        }
        // 正式流程开始 返回的二维码是带信息的，所以需要先接收商品信息
        // 比如:我是get过来商品的id，而后再进行查询数据库；这里大家随意；

        $order_sn = $this->request->get('order_sn');
        $total_price = $this->request->get('total_price');

        // 利用商品ID查询到商品名称和价格
        // 下面构造请求二维码的链接（由于是获取二维码支付，所以咋们请求的是native.php;后面会对该文件进行详细讲解）
        $url = 'http://huanchuang.softstao.com/framework/class/wxapi/payment/example/native.php?order_sn='.$order_sn.'&total_price='.$total_price;
        // 执行curlGet()函数
        $data = curlGet($url);
        // preg_match_all函数进行全局正则表达式匹配,获取到二维码的链接。
        preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$data,$matches);
        preg_match('/\|\|(.*)\|\|/',$matches[0],$aac);

        // 构造返回信息
        $obj['status'] = 'success';
        $obj['code'] = $aac[1];    // 此值为返回交易码【用来确认订单支付状态的】
        $obj['price'] = $total_price;
        $obj['msg'] = '/payment/example/'.$matches['2']; // 请求返回的二维码

        success($obj);// 返回json
    }

    //alipay获取二维码支付
    public function alipayqrcode()
    {
        // 配置参数
        $res = array();
//        $res['out_trade_no'] = $_POST['orderno'];   // 商户订单号        
//        $res['subject']  = $_POST['title'];   // 商品名称
//        $res['total_amount'] = $_POST['total'];   // 商品总价
//        $res['body'] = $_POST['description'];   // 商品描述

        $res['out_trade_no'] = '111111';   // 商户订单号        
        $res['subject']  = '纸尿裤';   // 商品名称
        $res['total_amount'] = 100;   // 商品总价
        $res['body'] = 'good';   // 商品描述

        $config = array();

        // 引入支付核心文件
        require_once(FRAMEWORK_PATH . '/class/wap_alipay/config.php');
        require_once(FRAMEWORK_PATH . '/class/wap_alipay/pagepay/service/AlipayTradeService.php');
        require_once(FRAMEWORK_PATH . '/class/wap_alipay/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php');

        // 获取支付宝配置参数
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $res["out_trade_no"];
        //订单名称，必填
        $subject = trim($res["subject"]);
        //付款金额，必填
        $total_amount = $res["total_amount"];
        //商品描述，可空
        $body = trim($res["body"]);
        //构造参数
        $payRequestBuilder = new \AlipayTradePagePayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $aop = new \AlipayTradeService($config);
        /**
         * pagePay 电脑网站支付请求
         * @param $builder 业务参数，使用buildmodel中的对象生成。
         * @param $return_url 同步跳转地址，公网可以访问
         * @param $notify_url 异步通知地址，公网可以访问
         * @return $response 支付宝返回的信息
        */
        $response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);
        //输出支付二维码
        var_dump($response);
}

	//检查订单状态
	public function check_order_status() {
		$order_sn = isset($_GET['order_sn']) ? trim($_GET['order_sn']) : '';
		$sql = "SELECT count(*) FROM {$this->tbp}order WHERE (order_sn='{$order_sn}' OR parent_order_sn='{$order_sn}')
			AND (pay_method='wxpay' OR pay_method='wxpay_h5') AND status>0";
		$count = $this->db->get_var($sql);
		success($count);
	}

	//获取折扣的手续费
	private function _get_service_money($city_id, $months, $type='') {
		$money = 0;
		if (strlen($type)) $type .= "_";
		$sql = "SELECT * FROM {$this->tbp}service_city WHERE city_id='{$city_id}'";
		$city = $this->db->get_row($sql);
		if ($city){
			$service_money = $type."service_money";
			$discount_months = $type."service_discount_month";
			$discount_months_money = $type."service_discount_month_money";
			if ($city->$discount_months>0 && $months>=$city->$discount_months) {
				$money = $city->$discount_months_money*$months;
			} else {
				$money = $city->$service_money*$months;
			}
			return round($money, 2);
		} else {
			error('找不到该城市');
		}
	}

	//下单成功后，需要调用此接口，用来更新库存和销量，并发送消息推送给卖家。
	public function order_complete($is_show=true, $notify_order_sn="") {
		//notify_order_sn: 从支付回调处返回来的订单单号，直接使用
		if ($notify_order_sn) {
			$parent_order_sn = $notify_order_sn;
		} else {
			$parent_order_sn = (isset($_GET['order_sn']) && trim($_GET['order_sn'])) ? trim($_GET['order_sn']) : '';
		}

		if ($parent_order_sn) {
			SQL::share()->log(true);
			//减少库存，增加销量，发送通知
			$sql = "SELECT o.* FROM {$this->tbp}order o
				WHERE o.status='1' AND (parent_order_sn='{$parent_order_sn}' OR order_sn='{$parent_order_sn}') AND handle_after_paid='0'";
			$orders = $this->db->get_results($sql);
			write_log($sql);
			write_log(serialize($orders));
			// print_r($orders);exit;
			if ($orders) {
				//更新订单处理后的标识，以后不再发送推送和更新销量。
				$sql = "UPDATE {$this->tbp}order SET handle_after_paid='1' WHERE parent_order_sn='{$parent_order_sn}' OR order_sn='{$parent_order_sn}'";
				$this->db->query($sql);
				write_log($sql);
				$order_ids = array();
				foreach ($orders as $k=>$o) {
					$order_ids[] = $o->id;
					//发送消息给用户
					if ($o->member_id) {
						// $this->send_notify_sms("您的订单{$o->order_sn}已经支付成功。", $o->member_id, $o->order_sn, $o->mobile);
						send_sms($o->mobile, "您的订单{$o->order_sn}已成功付款，新客户我们会在1-3个工作日内处理好并短信通知结果，续费客户直接等待查询到账即可。");
						//消费满了获取优惠卷
                        //找出有领取条件的优惠卷
                        $l_coupon = SQL::share('coupon')->where("man_price!=0")->find();
                        if ($l_coupon){
                            foreach ($l_coupon as $kk => $gg){
                                if ($o->total_price>$gg->man_price){
                                    $coupon_id[] = $gg->man_price;
                                }
                            }
                            $max_price = max($coupon_id);
                            //找出满足最大消费的优惠券
                            $max_coupon = SQL::share('coupon')->where("man_price='{$max_price}'")->order("id DESC")->row();
                            if ($max_coupon){
                                //每人限领
                                $got3 = SQL::share('coupon_sn')->where("coupon_id='{$max_coupon->id}' AND member_id='{$o->member_id}' AND member_id>0")->count();
                                if ($max_coupon->num_per_person==0 || $max_coupon->num_per_person>$got3){
                                    $status = $max_coupon->status;
                                    if ($status==0) $status = 1;
                                    $sn2 = date('m') . date('d') . substr(time(), -3) . substr(microtime(), 2, 6) . rand(100, 999);
                                    $r = SQL::share('coupon_sn')->insert(array('member_id'=>$o->member_id, 'coupon_id'=>$max_coupon->id, 'coupon_money'=>$max_coupon->coupon_money, 'sn'=>$sn2,
                                        'add_time'=>time(), 'get_time'=>time(), 'times'=>$max_coupon->times, 'status'=>$status));
                                    if ($r){
                                        send_sms($o->mobile, "感谢您对本店的支持，现有优惠券已经发至您帐下，可到小宝“个人中心”里的“我的优惠券”查看，一个月内都可使用哦。");
                                    }
                                }
                            }
                        }
                        //发放优惠卷
                        //查找该用户的邀请人
                        $m_id = SQL::share('member_invitation')->where("invitation_id='{$o->member_id}'")->val('member_id');
                        if ($m_id){
                            $coupon = SQL::share('coupon')->where("id='{$this->configs['coupon_id']}'")->row();
                            if ($coupon){
                                $get_num = $this->configs['get_num'];
                                //查找该用户邀请人获得优惠卷的次数
                                $time = SQL::share('member_invitation')->where("invitation_id='{$o->member_id}'")->val('time');
                                if ($get_num == -1 || $get_num>$time){
                                    $status = $coupon->status;
                                    if ($status==0) $status = 1;
                                    //每人限领
                                    $got = SQL::share('coupon_sn')->where("coupon_id='{$coupon->id}' AND member_id='{$m_id}' AND member_id>0")->count();
                                    if ($coupon->num_per_person==0 || $coupon->num_per_person>$got){
                                        $sn = date('m') . date('d') . substr(time(), -3) . substr(microtime(), 2, 6) . rand(100, 999);
                                        $rs = SQL::share('coupon_sn')->insert(array('member_id'=>$m_id, 'coupon_id'=>$coupon->id, 'coupon_money'=>$coupon->coupon_money, 'sn'=>$sn,
                                            'add_time'=>time(), 'get_time'=>time(), 'times'=>$coupon->times, 'status'=>$status));
                                        if ($rs){
                                            SQL::share('member_invitation')->where("invitation_id='{$o->member_id}'")->update(array('time'=>array('time','+1')));
                                            //获取邀请人的电话号码
                                            $m_order = SQL::share('order')->where("member_id='{$m_id}'")->order("id DESC")->row();
                                            if ($m_order){
                                                send_sms($m_order->mobile, "感谢您对本店的支持，现有优惠券已经发至您帐下，可到小宝“个人中心”里的“我的优惠券”查看，一个月内都可使用哦。");
                                            }
                                        }
                                    }
                                    $got2 = SQL::share('coupon_sn')->where("coupon_id='{$coupon->id}' AND member_id='{$o->member_id}' AND member_id>0")->count();
                                    if ($coupon->num_per_person==0 || $coupon->num_per_person>$got2){
                                        $sn1 = date('m') . date('d') . substr(time(), -3) . substr(microtime(), 2, 6) . rand(100, 999);
                                        $rs2 = SQL::share('coupon_sn')->insert(array('member_id'=>$o->member_id, 'coupon_id'=>$coupon->id, 'coupon_money'=>$coupon->coupon_money, 'sn'=>$sn1,
                                            'add_time'=>time(), 'get_time'=>time(), 'times'=>$coupon->times, 'status'=>$status));
                                        if ($rs2){
                                            send_sms($o->mobile, "感谢您对本店的支持，现有优惠券已经发至您帐下，可到小宝“个人中心”里的“我的优惠券”查看，一个月内都可使用哦。");
                                        }
                                    }
                                }
                            }
                        }
					}
					//插入/更新汇总表
					$c = SQL::share('collect_temporary')->where("order_id='{$o->id}'")->row();
					if ($c) {
						$collect = SQL::share('collect')->where("city_id='{$c->city_id}' AND idcard='{$c->idcard}'")->row();
						$months = $gmonths = array();
						if ($collect && strlen($collect->month)) $months = explode(',', str_replace('，', ',', $collect->month));
						$months = array_merge($months, explode(',', str_replace('，', ',', $c->month)));
						$months = $this->collect_mod->sortMonths($months);
						if ($collect && strlen($collect->gmonth)) $gmonths = explode(',', str_replace('，', ',', $collect->gmonth));
						$gmonths = array_merge($gmonths, explode(',', str_replace('，', ',', $c->gmonth)));
						$gmonths = $this->collect_mod->sortMonths($gmonths);
						if ($collect) {
							$collect_id = $collect->id;
							$status = $collect->status;
							if ($status==3 || $status==5) $status = 0;
							$gstatus = $collect->gstatus;
							if ($collect->gjj_price>0) {
								if ($gstatus==3 || $gstatus==5) {
									$gstatus = 0;
								}
							} else {
								$gstatus = 5;
							}
							SQL::share('collect')->where($collect_id)->update(array('member_type'=>$c->member_type, 'end_time'=>$c->end_time,
								'social_number'=>$c->social_number, 'gjj_number'=>$c->gjj_number, 'member_name'=>$c->member_name, 'person_type'=>$c->person_type,
								'mobile'=>$c->mobile, 'social_price'=>$c->social_price, 'gjj_price'=>$c->gjj_price, 'service_price'=>$c->service_price,
								'gjj_service_price'=>$c->gjj_service_price, 'total_price'=>$c->total_price, 'month'=>implode('，', $months),
								'gmonth'=>implode('，', $gmonths), 'casy_id'=>$c->casy_id, 'status'=>$status, 'gstatus'=>$gstatus));//, 'kstatus'=>0, 'gkstatus'=>0
						} else {
							$status = 0;
							if ($c->gjj_price>0) {
								$gstatus = 0;
							} else {
								$gstatus = 5;
							}
							$collect_id = SQL::share('collect')->insert(array('city_id'=>$c->city_id, 'member_type'=>$c->member_type, 'member_id'=>$c->member_id,
								'member_name'=>$c->member_name, 'begin_time'=>$c->begin_time, 'end_time'=>$c->end_time, 'real_name'=>$c->real_name, 'idcard'=>$c->idcard,
								'social_number'=>$c->social_number, 'gjj_number'=>$c->gjj_number, 'person_type'=>$c->person_type, 'mobile'=>$c->mobile,
								'social_price'=>$c->social_price, 'gjj_price'=>$c->gjj_price, 'service_price'=>$c->service_price,
								'gjj_service_price'=>$c->gjj_service_price, 'total_price'=>$c->total_price, 'month'=>implode('，', $months),
								'gmonth'=>implode('，', $gmonths), 'casy_id'=>$c->casy_id, 'add_time'=>time(), 'status'=>$status, 'gstatus'=>$gstatus));
							// echo SQL::share()->log;
							// echo $collect_id;exit;
						}
						$this->collect_mod->set_collect_month($collect_id);
					}
				}
				$order_ids = implode(',', $order_ids);
				//echo $order_ids;
				if ($order_ids) {
					$goods_ids = array();
					$sql = "SELECT og.goods_id, og.quantity, g.stocks
						FROM {$this->tbp}order_goods og INNER JOIN {$this->tbp}goods g ON g.id=og.goods_id
						WHERE og.order_id IN ({$order_ids})";
					$goods = $this->db->get_results($sql);
					if ($goods) {
						foreach ($goods as $k=>$g) {
							$status = 1;
							$stocks = $g->stocks - $g->quantity;
							if ($stocks <= 0)  {
								$stocks = 0;
								$status = 0; //下架
							}
							$sql = "UPDATE {$this->tbp}goods SET stocks='{$stocks}', status='{$status}', sales=sales+1 WHERE id='{$g->goods_id}'";
							//echo $sql."<br>";
							$this->db->query($sql);
							//同步所有下家的商品库存
							//$sql = "UPDATE {$this->tbp}goods SET stocks='{$stocks}', status='{$status}' WHERE parent_id='{$g->goods_id}'";
							//echo $sql."<br>";
							//$this->db->query($sql);
						}
					}
				}
			}
		}
		if ($is_show) success("ok");
	}

	//根据提交的产品数据来分单，返回分单后的店铺
	private function _split_shops() {
		$goods = $shops = $shop_ids = array();
		$goods_ids = "";
		$goods = (isset($_POST['goods']) && trim($_POST['goods'])) ? stripslashes($_POST['goods']) : '';
		//是否积分商城订单
		$integral_order = (isset($_POST['integral_order']) && trim($_POST['integral_order'])) ? trim($_POST['integral_order']) : 0;
		if (!$goods) error('请选择商品');
		$origin_goods = json_decode($goods);
		if (!$origin_goods) error('请选择商品');
		//$origin_goods = $origin_goods->goods;
		//print_r($origin_goods);
		//为了避免购买同一个产品的不同规格时，只显示一个产品的问题
		//直接查询, 每个产品查询一次，可能会导致效率问题
		$goods = array();
		foreach ($origin_goods as $k => $g) {
			$where = '';
			if (isset($g->spec)) {
				if (is_numeric($g->spec)) $where = " AND gs.id='{$g->spec}'";
				else $where = " AND gs.spec='{$g->spec}'";
			} else if ($integral_order) {
				$sql = "SELECT spec FROM {$this->tbp}goods_spec WHERE goods_id='{$g->goods_id}' ORDER BY id ASC LIMIT 1";
				$row = $this->db->get_row($sql);
				$where = " AND gs.spec='{$row->spec}'";
			}
			$sql = "SELECT g.id, g.name, g.pic, g.shop_id, g.integral, g.shipping_fee,
				gs.spec, 0 as quantity, gs.price, 0 as goods_price, gs.promote_price
				FROM {$this->tbp}goods g INNER JOIN {$this->tbp}goods_spec gs ON g.id=gs.goods_id
				WHERE g.id='{$g->goods_id}' {$where}";
			//echo $sql;
			$row = $this->db->get_row($sql);
			if ($row) {
				$row->quantity = intval($g->quantity);
				$row->price = $this->goods_mod->get_min_price(array($row->price, $row->promote_price));
				$row->goods_price = floatval($row->price) * $row->quantity;
				$goods[] = $row;
				$shop_ids[] = $row->shop_id;
			}
		}
		//print_r($goods);
		if (count($goods)) {
			//print_r($goods);
			//exit;
			$shop_ids = implode(',', $shop_ids);
			//if ($shop_ids) {
				$single_shop = false; //兼容单店铺的项目,清空店铺表里的所有记录或者goods表的shop_id设为0即自动转为单店铺
				$sql = "SELECT id as shop_id, name as shop_name, avatar as shop_avatar, 0 as shop_price, 0 as shipping_fee, NULL as goods
					FROM {$this->tbp}shop
					WHERE id IN ({$shop_ids})";
				$shops = $this->db->get_results($sql);
				if (!$shops) {
					$shop_obj = new stdClass();
					$shop_obj->shop_id = 0;
					$shop_obj->shop_price = 0;
					$shop_obj->shipping_fee = 0;
					$shop_obj->goods = NULL;
					$shops[0] = $shop_obj;
					$single_shop = true;
				}
				//计算每个店铺的商品价格
				foreach ($goods as $k=>$g) {
					foreach ($shops as $j=>$shop) {
						//兼容单店铺的项目
						if ($single_shop) {
							$shops[$j]->goods[] = $g;
							if ($integral_order) {
								//获取商品的积分
								$shops[$j]->shop_price += $g->integral * $g->quantity;
							} else {
								//获取商品的价格
								$shops[$j]->shop_price += $g->goods_price;
							}
						} else {
							//同一个店铺内的
							if ($g->shop_id==$shop->shop_id) {
								$shops[$j]->goods[] = $g;
								if ($integral_order) {
									$shops[$j]->shop_price += $g->integral * $g->quantity;
								} else {
									$shops[$j]->shop_price += $g->goods_price;
								}
								break;
							}
						}
					}
				}
				//计算每个店铺的运费
				foreach ($shops as $k=>$shop) {
					$shops[$k]->shipping_fee = $this->caculate_shipping_fee($shop->goods);
					if ($integral_order) $shops[$k]->shipping_fee = 0; //积分商城订单免运费
					if ($shops[$k]->shipping_fee) {
						$shops[$k]->shop_price += $shops[$k]->shipping_fee;
					}
				}
			//}
		}
		//$shops = add_domain_deep($shops, array("pic"));
		return $shops;
	}

	//获取订单总价
	private function _get_total_price($shops) {
		$shop_price = 0;
		if ($shops) {
			foreach ($shops as $k=>$shop) {
				$shop_price += $shop->shop_price;
			}
		}
		return $shop_price;
	}

	//判断该会员是否该店铺的批发会员
	public function is_reseller($shop_id) {
		$sql = "SELECT count(*) FROM {$this->tbp}shop_reseller WHERE shop_id='{$shop_id}' AND member_id='{$this->member_id}'";
		return intval($this->db->get_var($sql));
	}

	//计算运费，只计算商品里运费最高的
	public function caculate_shipping_fee($goods) {
		$shipping_fee = 0;
		if ($goods) {
			foreach ($goods as $k=>$g) {
				if ($g->shipping_fee>$shipping_fee) {
					$shipping_fee = $g->shipping_fee;
				}
			}
		}
		return $shipping_fee;
	}

	//检测订单的商品是否还可购买
	//该函数用在我的订单列表里未支付的订单进行支付时，判断商品库存是否足够、商品是否下架等
	public function check_order_goods() {
		$order_id = (isset($_GET['order_id']) && intval($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		if ($this->member_id<=0) error('请登录', -100);
		if ($order_id<=0) error('数据错误');
		$sql = "SELECT og.shop_id, og.goods_id, og.goods_name, g.stocks, g.status, g.id, og.quantity
			FROM {$this->tbp}order_goods og INNER JOIN {$this->tbp}order o ON og.order_id=o.id
			LEFT JOIN {$this->tbp}goods g ON og.goods_id=g.id
			WHERE o.id='{$order_id}' AND o.member_id='{$this->member_id}'";
		$goods = $this->db->get_results($sql);
		if (!$goods) error('订单商品已经失效');
		foreach ($goods as $k => $g) {
			$goods_name = mb_substr($g->goods_name, 0, 6);
			if (!intval($g->id)) error("商品（{$goods_name}）已经失效");
			if (intval($g->stocks) <= 0) error("商品（{$goods_name}）已经下架");
			if (intval($g->status) == 0) error("商品（{$goods_name}）已经下架");
			if ($g->quantity > $g->stocks) error("商品（{$goods_name}）库存不足");
		}
		$sql = "SELECT id, order_sn, total_price, pay_method FROM {$this->tbp}order WHERE id='{$order_id}'";
		$row = $this->db->get_row($sql);
		success($row);
	}

	//根据shops数组来获取goods_id的数组
	private function _get_goods_ids($shops) {
		$ids = array();
		if ($shops) {
			foreach ($shops as $key => $shop) {
				if ($shop->goods) {
					foreach ($shop->goods as $j => $goods) {
						$ids[] = $goods->id;
					}
				}
			}
			$ids = array_unique($ids);
		}
		return $ids;
	}
}
